package com.example.lotteryticketdev.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.lotteryticketdev.dao.LuckyBallDao;
import com.example.lotteryticketdev.entity.LuckyBall;
import com.example.lotteryticketdev.entity.Prize;
import com.example.lotteryticketdev.service.LuckyBallService;
import com.example.lotteryticketdev.service.PrizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * (LuckyBall)表服务实现类
 *
 * @author makejava
 * @since 2023-09-25 19:26:00
 */
@Service("LuckyBallService")
public class LuckyBallServiceImpl extends ServiceImpl<LuckyBallDao, LuckyBall> implements LuckyBallService {

    @Autowired
    private PrizeService prizeService;

    @Autowired
    private LuckyBallDao luckyBallDao;

    @Override
    public boolean saveLuckyBall(List<LuckyBall> list) {

        AtomicReference<Integer> count = new AtomicReference<>(0);
        list.forEach(luckyBall -> {
            this.baseMapper.insert(luckyBall);
            List<Prize> prizes = luckyBall.getPrizes();
            Long id = luckyBall.getId();
            prizes.forEach(prize -> {
                prize.setParentId(id);
                prizeService.save(prize);
            });
            count.getAndSet(count.get() + 1);
        });
        return list.size() == count.get() ? true : false;
    }

    @Override
    public List<Map<String,Integer>> findEveryBallCount() {
        List<LuckyBall> list = this.baseMapper.selectList(new QueryWrapper<LuckyBall>());
        List<Map<String,Integer>> mapsList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            Map<String, Integer> countMap = new HashMap<>();
            mapsList.add(countMap);
        }
        // 红色球计数  => 放入第 1~6 个 map中
        list.stream().forEach(luckyBall -> {
            String red = luckyBall.getRed();
            // "07,09,15,16,17,26"
            /*
                1     2    3    4    5   6
            * ["07","09","15","16","17",26"]
            * ["01","02","13","18","25",27"]
            * */
            String[] split = red.split(",");
            int i = 0 ;
            for (; i < split.length ; i++) {
               String s = split[i];
               Map<String, Integer> countMap = mapsList.get(i);
                if( countMap.containsKey(s) ){
                    Integer count = countMap.get(s);
                    countMap.put(s, ++count);
                }else {
                    countMap.put(s, 1);
                }

            }
            //蓝色球计数  => 放入第 7 个 map中
            Map<String, Integer> countMap = mapsList.get(i);
            String blue = luckyBall.getBlue();
            if( countMap.containsKey(blue) ){
                Integer count = countMap.get(blue);
                countMap.put(blue, ++count);
            }else {
                countMap.put(blue, 1);
            }

        });
        return mapsList;
    }

    @Override
    public List<List<Integer>> findEveryBallCountPlus() {
        List<Map<String, Integer>> everyBallCount = this.findEveryBallCount();
        return this.sort(everyBallCount);
    }

    @Override
    public LuckyBall findMaxCodeLuckyBall() {
        Integer code = luckyBallDao.selectMaxCode();
        QueryWrapper<LuckyBall> wrapper = new QueryWrapper<>();
        wrapper.eq("code",code);
        LuckyBall one = this.baseMapper.selectOne(wrapper);
        return one;
    }

    @Override
    public LuckyBall findMaxProbabilityOne() {
        List<List<String>> maxProbabilityList = this.findMaxProbabilityList();
        LuckyBall luckyBall = new LuckyBall();
        StringBuilder red = new StringBuilder();
        String blue = "";
        int index = 0 ;
        for (List<String> list : maxProbabilityList) {
            if(index < 6){
                red.append(list.get(0));
                if (index != 5 ){
                    red.append(",");
                }
            }else {
                blue = list.get(0);
                break;
            }
            index++;
        }
        luckyBall.setRed(red.toString());
        luckyBall.setBlue(blue);
        return luckyBall;
    }

    @Override
    public  List<List<String>> findMaxProbabilityList() {
        List<List<String>> parentPool = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            List<String> sonPool = new ArrayList<>();
            parentPool.add(sonPool);
        }
        //把7组概率最高的3个数获取
        List<List<Integer>> parent = this.findEveryBallCountPlus();
        int i = 0 ;
        for (List<Integer> balls : parent) {

            for (int j = 0; j < 3; j++) {
                //获取最大次数
                Integer maxValue = balls.stream().max(Comparator.naturalOrder()).get();
                //通过最大次数获取最大次数的索引
                int maxIndex = balls.indexOf(maxValue);
                //删除最大次数（可能存在多个相同的最大次数）
                balls.set(maxIndex,-1);
                //拿到一号球放入最大的三个频次的值
                parentPool.get(i).add(maxIndex + 1+ "");
                //检测是否还有相同次数的值
            }
            i++;

        }
        System.out.println("parentPool = " + parentPool);
        return parentPool;
    }

    @Override
    public LuckyBall findRandomLuckyBall() {
        List<List<String>> parent = this.findMaxProbabilityList();
        Random random = new Random();
        StringBuilder red = new StringBuilder();
        LuckyBall luckyBall = new LuckyBall();
        for (int i = 0; i < parent.size()-1; i++) {
            List<String> son = parent.get(i);
            String s = son.get(random.nextInt(3));
            red.append(s);
            if (i < parent.size()-2){
                red.append(",");
            }
        }
        luckyBall.setRed(red.toString());
        luckyBall.setBlue(parent.get(parent.size()-1).get(random.nextInt(3)));
        return luckyBall;
    }

    private List<List<Integer>> sort(List<Map<String,Integer>> list){
        List<List<Integer>>  parent = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            List<Integer> son = new ArrayList<>();
            for (int j = 0; j < 33; j++) {
                son.add(0);
            }
            parent.add(son);
        }
        //记录是第位球
        int i = 0 ;
        //遍历第一个map,第一个map记录者1号位的所有数字情况
        for (Map<String, Integer> tempMap : list) {

            List<Integer> integers = parent.get(i);

            Set<Map.Entry<String, Integer>> entries = tempMap.entrySet();
            for (Map.Entry<String, Integer> entry : entries) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                Integer index = 0 ;
                if (key.startsWith("0")){
                    //获取球的号码，把号码作为索引放到son里面
                  String indexStr =  key.replace("0","");
                  index = Integer.valueOf(indexStr) - 1 ;
                }else {
                   index =  Integer.valueOf(key) - 1 ;
                }
                integers.set(index,value);
            }

            i++;
        }

        return parent;
    }


}

